﻿using System;
using System.Drawing;

namespace Spencen.Mobile.Markup.Converters
{
    public class ImageConverter : Converter<Image>
    {
        #region IConverter<Image> Members

        public override Image ConvertFromString( string input, Type toType )
        {
            var inputs = input.Split( ',' );
            var lastPeriod = inputs[ 0 ].LastIndexOf( '.' );
            var baseName = inputs[ 0 ].Substring( 0, lastPeriod );
            var imageName = inputs[ 0 ].Substring( lastPeriod + 1 );
            var assemblyName = inputs[ 1 ];
            var assembly = System.Reflection.Assembly.Load( assemblyName );

            Image image;
            // Via resource manager (e.g. added as project resource)
            if ( baseName.EndsWith("Properties.Resources" ) )
            {
                var resourceManager = new System.Resources.ResourceManager( baseName, assembly );
                image = (Image) resourceManager.GetObject( imageName );
            }
            else
            {
                using ( var stream = assembly.GetManifestResourceStream( baseName + "." + imageName ) )
                {
                    image = new Bitmap( stream );
                }
            }

            return (Image)image;
        }

        #endregion
    }
}
